<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right" style="font-size: 16px">
      <el-breadcrumb-item :to="{ path: '/sys-admin/home' }">
        <i class="el-icon-s-promotion"></i> 后台管理
      </el-breadcrumb-item>
      <el-breadcrumb-item>添加轮播图</el-breadcrumb-item>
    </el-breadcrumb>

    <el-divider></el-divider>

    <el-form :model="ruleForm"  ref="ruleForm" label-width="100px" class="demo-ruleForm">

      <el-upload
          action="http://localhost:9080/upload"
          name="picFile"
          :limit=1
          accept=".png, .jpg, .jpeg"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-success="handleSuccess"
          :on-remove="handleRemove">
        <i class="el-icon-plus"></i>
      </el-upload>
      <el-dialog :visible.sync="dialogVisible">
        <img width="100%" :src="dialogImageUrl" alt="">
      </el-dialog>
      <el-button type="success" @click="submitForm('ruleForm')">上传图片</el-button>

    </el-form>
  </div>

</template>

<script>
export default {
  data() {
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      ruleForm: {
        url: ""
      }
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {

          let urls = 'http://localhost:9080/banners/add-new';
          console.log("urls=" + urls);
          console.log("url=" + this.ruleForm.url);

          let formData = this.qs.stringify(this.ruleForm);

          console.log("当前formData=" + formData);

          this.axios.post(urls, formData).then((response) => {
            console.log("到这儿了")
            let jsonResult = response.data;
            if (jsonResult.state == 20000) {

              this.$message({
                message: '添加轮播图成功！',
                type: "success"
              })
              this.$router.replace('/admin');

            } else {
              this.$alert(jsonResult.message, '操作失败', {
                confirmButtonText: '确定',
                callback: action => {
                }
              });
            }
          })

        } else {
          this.$alert("请填写完整信息", '操作失败', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });

        }
      })


    },
    handleSuccess(response, file, fileList) {

      console.log("当前url=" + this.ruleForm.url);


      this.ruleForm.url = file.response;
      console.log(this.ruleForm.url);

    },
    goBack() {
      //返回上一页面
      history.back();
    },
    handleRemove(file, fileList) {

      let urls = 'http://localhost:9080/remove?url=' + file.response;
      console.log("urls=" + urls);
      // let formData = this.qs.stringify(file.response);

      this.axios.get(urls).then((response) => {
        console.log("删除成功！");
      })
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    }
  }
}
</script>
